package com.guaoran.study.future;

import com.guaoran.study.map.struct.one.User;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;

/**
 * @Desc： todo xxx
 * @Auth gucheng
 * @Date 2020/11/4 下午5:14.
 */
public class CompletableFutureExceptionDemo {
    public static void main(String[] args) {
        ExecutorService executor =
                Executors.newFixedThreadPool(3);
        test(executor);
        executor.shutdown();

        System.out.println("=========");
        System.out.println("eeeeeee");

    }


    public static String doSaveInvoiceExtend(int age){
        if(age%3==0){
            throw new RuntimeException("random exception");
        }
        return age+"---";
    }

    public static  void test(ExecutorService executor){
        List<User> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(new User(i));
        }

        List<CompletableFuture<String>> futures = new ArrayList<>();
        for (User inner : list) {
            CompletableFuture future = CompletableFuture.supplyAsync((Supplier<String>)() -> {
                String age = String.valueOf(inner.getAge());
                return doSaveInvoiceExtend(Integer.parseInt(age));
            },executor).exceptionally(e->{
                return null;
            });
            futures.add(future);
        }
        CompletableFuture<Void> allCompletableFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));
        allCompletableFuture.join();
        System.out.println("=====");
    }
}
